package com.banyou.banyou.login.regist;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TextInputLayout;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.banyou.banyou.R;
import com.banyou.banyou.base.BaseActivity;
import com.banyou.banyou.util.ShowAddressPicker;
import com.banyou.banyou.util.ShowToast;
import com.banyou.banyou.webutils.ProgressSubscriber;
import com.banyou.banyou.webutils.SubscriberOnErrorListener;
import com.banyou.banyou.webutils.SubscriberOnNextListener;
import com.banyou.banyou.webutils.UpLoadImage;
import com.socks.library.KLog;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.qqtheme.framework.entity.City;
import cn.qqtheme.framework.entity.County;
import cn.qqtheme.framework.entity.Province;
import cn.qqtheme.framework.picker.NumberPicker;
import cn.qqtheme.framework.picker.OptionPicker;

/**
 * ----------Dragon be here!----------/
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃神兽保佑
 * 　　　　┃　　　┃代码无BUG！
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━神兽出没━━━━━━
 * 类描述：
 * 创建人：Random
 * 修改时间：
 * 修改备注：
 */

public class RegistActivity extends BaseActivity<RegistPresenter> implements RegistContract.View, View.OnClickListener {

    @BindView(R.id.back)
    ImageView mBack;
    @BindView(R.id.head_img)
    ImageView mHeadImg;
    @BindView(R.id.head_content)
    LinearLayout mHeadContent;
    @BindView(R.id.card_img)
    ImageView mCardImg;
    @BindView(R.id.card_content)
    LinearLayout mCardContent;
    @BindView(R.id.edit_name)
    EditText mEditName;
    @BindView(R.id.edit_name_content)
    TextInputLayout mEditNameContent;
    @BindView(R.id.edit_password)
    EditText mEditPassword;
    @BindView(R.id.edit_password_content)
    TextInputLayout mEditPasswordContent;
    @BindView(R.id.edit_phone)
    EditText mEditPhone;
    @BindView(R.id.edit_phone_content)
    TextInputLayout mEditPhoneContent;
    @BindView(R.id.edit_code)
    EditText mEditCode;
    @BindView(R.id.edit_code_content)
    TextInputLayout mEditCodeContent;
    @BindView(R.id.edit_userCode)
    EditText mEditUserCode;
    @BindView(R.id.edit_userCode_content)
    TextInputLayout mEditUserCodeContent;
    @BindView(R.id.regist_button)
    Button mRegistButton;
    @BindView(R.id.send_code_btn)
    Button mSendCodeBtn;
    @BindView(R.id.title_bar)
    RelativeLayout mTitleBar;
    @BindView(R.id.spinner)
    Spinner mSpinner;
    @BindView(R.id.info_content)
    LinearLayout mInfoContent;
    @BindView(R.id.city_btn)
    Button mCityBtn;
    @BindView(R.id.edit_remark)
    EditText mEditRemark;
    @BindView(R.id.edit_remark_content)
    TextInputLayout mEditRemarkContent;
    @BindView(R.id.age_button)
    Button mAgeButton;
    @BindView(R.id.sex_button)
    Button mSexButton;
    private int mType;//1是游客，2是伴游
    private final int HEAD_REQUEST_CODE = 0x110;
    private final int CARD_REQUEST_CODE = 0x220;
    private AlertDialog mCardDialog, mHeadDialog;
    private View mView;
    private String mCardImageName, mHeadImageName;
    private int mCertType = 1;
    private String[] mStr;
    private String mCityCode;
    private int mAge;
    private String mSex;

    @Override
    protected RegistPresenter initPresenter() {
        return new RegistPresenter();
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_regist;
    }

    @Override
    protected View initLayoutView() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter.initPresenter(this, new RegistModel());
        ButterKnife.bind(this);
        Intent intent = getIntent();
        if (intent != null) {
            mType = intent.getIntExtra("type", 0);
        }

        if (mType == 1) {
            user();//游客界面
        }
        initSpinner();//初始化Spinner
        createDialogView();//创建Dialog点击的两个button
        initEditListener();//初始化EditTextListener
    }

    /**
     * 初始化Spinner
     */
    private void initSpinner() {
        mStr = new String[3];
        mStr[0] = "身份证";
        mStr[1] = "护照";
        mStr[2] = "军人证";
        mSpinner.setAdapter(new ArrayAdapter<String>(RegistActivity.this, android.R.layout.simple_list_item_1, mStr));
        mSpinner.setSelection(0);
        mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mEditUserCode.setText("");
                mEditUserCodeContent.setHint("请输入" + mStr[position] + "号");
                mCertType = position + 1;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    /**
     * 创建Dialog点击的两个button
     */
    private void createDialogView() {
        mView = LayoutInflater.from(this).inflate(R.layout.chose_pictor_dialog, null);
        ViewHolder holder = new ViewHolder(mView);
        holder.mCameraBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCardDialog != null && mCardDialog.isShowing()) {
                    GalleryFinal.openCamera(CARD_REQUEST_CODE, mCardCallBack);
                    mCardDialog.dismiss();
                } else {
                    GalleryFinal.openCamera(HEAD_REQUEST_CODE, mHeadCallBack);
                    mHeadDialog.dismiss();
                }
            }
        });
        holder.mChooseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCardDialog != null && mCardDialog.isShowing()) {
                    GalleryFinal.openGallerySingle(CARD_REQUEST_CODE, mCardCallBack);
                    mCardDialog.dismiss();
                } else {
                    GalleryFinal.openGallerySingle(HEAD_REQUEST_CODE, mHeadCallBack);
                    mHeadDialog.dismiss();
                }
            }
        });
    }

    /**
     * 初始化EditTextListener
     */
    private void initEditListener() {
        mEditName.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                mEditPassword.requestFocus();
                return true;
            }
        });
        mEditPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                mEditPhone.requestFocus();
                return true;
            }
        });
        mEditPhone.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                mEditCode.requestFocus();
                return true;
            }
        });
        mEditCode.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                mEditUserCode.requestFocus();
                return true;
            }
        });
        mEditUserCode.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                regist();//注册！
                return true;
            }
        });
    }

    /**
     * 注册
     */
    private void regist() {
        //用户名判断
        if (mEditName.getText().length() < 2) {
            Toast.makeText(this, "用户名必须大于或等于2位", Toast.LENGTH_SHORT).show();
            return;
        }

        //电话号判断
        if (!isPhoneNum(mEditPhone.getText().toString())) {
            Toast.makeText(this, "电话号码输入有误", Toast.LENGTH_SHORT).show();
            return;
        }
        //其他判空
        if (TextUtils.isEmpty(mEditPhone.getText()) ||
                TextUtils.isEmpty(mEditCode.getText()) ||
                TextUtils.isEmpty(mEditName.getText()) ||
                TextUtils.isEmpty(mEditPassword.getText())
                ) {
            Toast.makeText(this, "请输入全部内容", Toast.LENGTH_SHORT).show();
            return;
        }
//        if(mHeadImageName==null||mHeadImageName.length()==0){
//            Toast.makeText(this, "请上传头像", Toast.LENGTH_SHORT).show();
//            return ;
//        }
        //如果是伴游，增加判断选项
        if (mType == 2) {
            //身份证判断
            if (!isUserCard(mEditUserCode.getText().toString())) {
                Toast.makeText(this, "身份证输入有误", Toast.LENGTH_SHORT).show();
                return;
            }
            //身份证上传判断
//            if (mCardImageName == null || mCardImageName.length() == 0) {
//                Toast.makeText(this, "请上传手持身份证照片", Toast.LENGTH_SHORT).show();
//                return ;
//            }
            //身份证号码判空
            if (TextUtils.isEmpty(mEditUserCode.getText())) {
                Toast.makeText(this, "请输入身份证", Toast.LENGTH_SHORT).show();
                return;
            }

            if (mCityCode == null || mCityCode.length() == 0) {
                ShowToast.showToast("请输入城市信息");
                return;
            }

            if (mEditRemark.getText().toString().trim().length() == 0) {
                ShowToast.showToast("请输入个人简介");
                return;
            }

            if(mAge==0){
                ShowToast.showToast("请选择年龄");
                return;
            }

            if(mSex==null){
                ShowToast.showToast("请选择性别");
                return ;
            }
        }
        Map<String, String> map = new HashMap<>();
        if (mType == 1) {
            map.put("userName", mEditName.getText().toString());
            map.put("billId", mEditPhone.getText().toString());
            map.put("password", mEditPassword.getText().toString());
            map.put("userType", mType + "");
            map.put("randomCode", mEditCode.getText().toString());
            map.put("portalImagPath", "./fake_image_path");
        } else {
            map.put("userName", mEditName.getText().toString());
            map.put("billId", mEditPhone.getText().toString());
            map.put("password", mEditPassword.getText().toString());
            map.put("userType", mType + "");
            map.put("randomCode", mEditCode.getText().toString());
            map.put("certType", mCertType + "");
            map.put("certNo", mEditUserCode.getText().toString());
            map.put("portalImagPath", "./fake_image_path");
            map.put("idCardImagePath", "./fake_image_path2");
            map.put("regionId", mCityCode);
            map.put("remarks", mEditRemark.getText().toString());
            map.put("sex",mSex);
            map.put("age",mAge+"");
        }

        mPresenter.regist(map);

    }


    /**
     * 游客界面
     */
    private void user() {
        mCardContent.setVisibility(View.GONE);
        mEditUserCodeContent.setVisibility(View.GONE);
        mCityBtn.setVisibility(View.GONE);
        mSpinner.setVisibility(View.GONE);
        mAgeButton.setVisibility(View.GONE);
        mSexButton.setVisibility(View.GONE);
        mEditRemarkContent.setVisibility(View.GONE);
    }

    @Override
    protected String pageName() {
        return "注册页面";
    }

    /**
     * 点击事件
     *
     * @param v
     */
    @OnClick({R.id.back, R.id.regist_button, R.id.send_code_btn, R.id.card_img, R.id.head_img, R.id.city_btn,R.id.age_button,R.id.sex_button})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                this.finish();//回退
                break;
            case R.id.regist_button:
                regist();//注册
//                registFile();
                break;
            case R.id.send_code_btn:
                sendCode();//发送验证码
                break;
            case R.id.card_img:
                createCardDialog();
                break;
            case R.id.head_img:
                createHeadDialog();
                break;
            case R.id.city_btn:
                showWeelDialog();
                break;
            case R.id.age_button:
                showAgeDialog();
                break;
            case R.id.sex_button:
                showSexDialog();
                break;
        }

    }

    /**
     * 性别选择器
     */
    private void showSexDialog() {
        OptionPicker picker=new OptionPicker(this,new String[]{"男","女"});
        picker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                if(index==0) {
                    mSex = "M";
                }else{
                    mSex="F";
                }
                mSexButton.setText("性别："+item);
            }
        });
        picker.show();
    }

    /**
     * 显示年龄dialog
     */
    private void showAgeDialog() {
        NumberPicker picker=new NumberPicker(this);
        picker.setRange(10,99);
        picker.setSelectedItem(18);
        picker.setLabel("岁");
        picker.setOnNumberPickListener(new NumberPicker.OnNumberPickListener() {
            @Override
            public void onNumberPicked(int index, Number item) {
                mAge=item.intValue();
                mAgeButton.setText("年龄:"+item.intValue()+"岁");
            }
        });
        picker.show();
    }

    private void registFile() {
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera/IMG_20170523_142646.jpg");
        UpLoadImage.filesToMultipartBody("file", new String[]{file.getAbsolutePath()}, new SubscriberOnNextListener() {
            @Override
            public void onNext(Object o) {
                KLog.a("success");
            }
        }, new SubscriberOnErrorListener() {
            @Override
            public void onError(Throwable e) {
                KLog.a("fail=" + e.getMessage());
            }

            @Override
            public void onError() {

            }
        }, this);
    }

    /**
     * 显示WeelDialog
     */
    private void showWeelDialog() {
        ShowAddressPicker.show(this, new ShowAddressPicker.OnCityPickedCallBack() {
            @Override
            public void onAddressPicked(Province province, City city, County county) {
                mCityBtn.setText("你的位置：" + province.getName() + "-" + city.getName());
                //TODO 记录CityCode
                mCityCode = (String) city.getId();
            }
        });
    }


    /**
     * 创建HeadDialog
     */
    private void createHeadDialog() {
        createDialogView();
        if (mHeadDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            mHeadDialog = builder.setTitle("请选择类型")
                    .setCancelable(true)
                    .setMessage("选择拍照，或直接从相册中选择")
                    .setView(mView)
                    .create();
            mHeadDialog.getWindow().setBackgroundDrawable(getResources().getDrawable(R.drawable.alert_dialog_alpha_drawable));
        }
        mHeadDialog.show();
    }

    /**
     * 处理身份证上传图片
     */
    private GalleryFinal.OnHanlderResultCallback mCardCallBack = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
            Bitmap bitmap = BitmapFactory.decodeFile(resultList.get(0).getPhotoPath());
            mCardImg.setImageBitmap(bitmap);
            mPresenter.uploadCard(resultList.get(0).getPhotoPath());
        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {
            Toast.makeText(RegistActivity.this, "图片打开失败", Toast.LENGTH_SHORT);
        }
    };


    /**
     * 处理头像上传图片
     */
    private GalleryFinal.OnHanlderResultCallback mHeadCallBack = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
            Bitmap bitmap = BitmapFactory.decodeFile(resultList.get(0).getPhotoPath());
            mHeadImg.setImageBitmap(bitmap);
        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {
            Toast.makeText(RegistActivity.this, "图片打开失败", Toast.LENGTH_SHORT);
        }
    };

    /**
     * 创建CardDialog
     */
    private void createCardDialog() {
        createDialogView();
        if (mCardDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            mCardDialog = builder.setTitle("请选择类型")
                    .setCancelable(true)
                    .setMessage("选择拍照，或直接从相册中选择")
                    .setView(mView)
                    .create();
            mCardDialog.getWindow().setBackgroundDrawable(getResources().getDrawable(R.drawable.alert_dialog_alpha_drawable));
        }
        mCardDialog.show();
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    mTimeCount--;
                    mSendCodeBtn.setClickable(false);
                    mSendCodeBtn.setText(mTimeCount + "秒后重发");
                    break;
                case 1:
                    mTimeCount = 60;
                    mSendCodeBtn.setClickable(true);
                    mSendCodeBtn.setText("重新发送");
                    break;
            }
        }
    };
    private int mTimeCount = 60;//倒计时

    /**
     * 点击发送验证码，倒计时60秒
     */
    private void countTime() {
        mTimeCount = 60;
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (mTimeCount > 0) {
                    mHandler.sendEmptyMessage(0);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                mHandler.sendEmptyMessage(1);
            }
        });
        thread.start();
    }

    /**
     * 发送验证码逻辑
     */
    private void sendCode() {
        String phoneNum = mEditPhone.getText().toString();
        if (TextUtils.isEmpty(phoneNum)) {
            Toast.makeText(this, "请先输入手机号", Toast.LENGTH_SHORT).show();
            return;
        }

        mPresenter.getCode(phoneNum);//发送验证码
    }

    /**
     * 正则表达式
     * 判断电话号码是否有误
     *
     * @param phoneNum
     * @return
     */
    public static boolean isPhoneNum(String phoneNum) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9])|(17[0-9]))\\d{8}$");
        Matcher m = p.matcher(phoneNum);
        return m.matches();
    }

    /**
     * 身份证正则表达式
     *
     * @param userCard
     * @return
     */
    public boolean isUserCard(String userCard) {
        if (userCard.length() == 15) {
            Pattern p = Pattern.compile("^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$");
            Matcher m = p.matcher(userCard);
            return m.matches();
        } else if (userCard.length() == 18) {
            Pattern p = Pattern.compile("^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$");
            Matcher m = p.matcher(userCard);
            return m.matches();
        } else {
            return false;
        }
    }

    /**
     * 获取验证码成功
     */
    @Override
    public void getCodeSuccess() {
        countTime();
        Toast.makeText(this, "获取验证码成功", Toast.LENGTH_SHORT).show();
    }

    /**
     * 获取验证码失败
     */
    @Override
    public void getCodeFail() {
        Toast.makeText(this, "获取验证码失败", Toast.LENGTH_SHORT).show();
    }

    /**
     * 上传身份证成功
     */
    @Override
    public void uploadCardSuccess(String fileName) {
        mCardImageName = fileName;
    }

    /**
     * 上传身份证失败
     */
    @Override
    public void uploadCardFail(Throwable e) {
        if (e instanceof ProgressSubscriber.ReturnCodeErrorException) {
            ShowToast.showToast(((ProgressSubscriber.ReturnCodeErrorException) e).getMsg());
        } else {
            Toast.makeText(this, "上传失败，请重新上传", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 上传头像成功
     *
     * @param fileName
     */
    @Override
    public void uploadHeadSuccess(String fileName) {
        mHeadImageName = fileName;
    }

    /**
     * 上传头像失败
     */
    @Override
    public void uploadHeadFail(Throwable e) {
        if (e instanceof ProgressSubscriber.ReturnCodeErrorException) {
            ShowToast.showToast(((ProgressSubscriber.ReturnCodeErrorException) e).getMsg());
        } else {
            Toast.makeText(this, "上传失败，请重新上传", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 注册成功
     */
    @Override
    public void registSuccess() {
        Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
        finish();
    }

    /**
     * 注册失败
     */
    @Override
    public void registFail(Throwable e) {
        if (e instanceof ProgressSubscriber.ReturnCodeErrorException) {
            ShowToast.showToast(((ProgressSubscriber.ReturnCodeErrorException) e).getMsg());
        } else {
            Toast.makeText(this, "注册失败", Toast.LENGTH_SHORT).show();
        }

    }

    static class ViewHolder {
        @BindView(R.id.choose_btn)
        Button mChooseBtn;
        @BindView(R.id.camera_btn)
        Button mCameraBtn;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
